using System;
using RomanJendrusz.Amazon.ETL.Domain;
using RomanJendrusz.Amazon.ETL.Infrastructure.DataBase;
using System.Linq;

namespace RomanJendrusz.Amazon.ETL.Repositories
{
    public class BrowseNodeRepository: Repository<Domain.BrowseNode, int>, IBrowseNodeRepository
    {
        private IQuerySource<BrowseNodesBook> browseNodesBooks;
        public BrowseNodeRepository(ISession session)
            : base(session, s => s.BrowsNodes, "BrowseNodeId")
        {
            browseNodesBooks = session.BrowsNodesBooks;
        }

        public BrowseNode AttachIfAllreadyExists(BrowseNode item)
        {
            BrowseNode node = FindBy(item.BrowseNodeId);
            if(node!= null)
            {
                foreach (var book in item.Books)
                {
                    if (session.BrowsNodesBooks.Where(bn => bn.Node == node && bn.Book == book).Count() == 0)
                       {
                        node.AddBook(book);
                    }
                }
                return node;
            }
            node = item;
            while( node.ParentNode != null)
            {
                BrowseNode persistedNode = FindBy(node.ParentNode.BrowseNodeId);
                if(persistedNode != null)
                {
                    node.ParentNode = persistedNode;
                    return item;
                }
                node = node.ParentNode;
            }
            return item;
        }

        public bool Contains(BrowseNode node, Book aBook)
        {
            if (node == null) throw new ArgumentNullException("node");
            if (aBook == null) throw new ArgumentNullException("aBook");
            return browseNodesBooks.Where(bn => bn.Book == aBook && bn.Node == node).Count() > 0;
        }
    }
}